<template>
  <el-card shadow="always" :body-style="{ padding: '20px' }">
    <el-form label-width="80px">
      <el-form-item label="SPU 名称">
        <span>{{ spuInfo.spuName }}</span>
      </el-form-item>
      <el-form-item label="SKU 名称">
        <el-input
          placeholder="请输入Sku名称"
          v-model="skuInfo.skuName"
        ></el-input>
      </el-form-item>
      <el-form-item label="价格(元)">
        <el-input
          placeholder="请输入价格"
          type="number"
          v-model="skuInfo.price"
        ></el-input>
      </el-form-item>
      <el-form-item label="重量(克)">
        <el-input
          placeholder="请输入重量"
          type="number"
          v-model="skuInfo.weight"
        ></el-input>
      </el-form-item>
      <el-form-item label="规格描述">
        <el-input
          placeholder="请输入规格描述"
          type="textarea"
          v-model="skuInfo.skuDesc"
        ></el-input>
      </el-form-item>
      <el-form-item label="平台属性">
        <el-form label-width="80px" :inline="true">
          <el-form-item
            :label="attr.attrName"
            v-for="attr in attrList"
            :key="attr.id"
          >
            <el-select placeholder="请选择" v-model="attr.attrIdValueId">
              <el-option
                v-for="item in attr.attrValueList"
                :key="item.id"
                :value="`${item.attrId}:${item.id}`"
                :label="item.valueName"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-form label-width="80px" :inline="true">
          <el-form-item
            :label="saleAttr.saleAttrName"
            v-for="saleAttr in saleAttrList"
            :key="saleAttr.id"
          >
            <el-select
              placeholder="请选择"
              v-model="saleAttr.saleAttrIdValueId"
            >
              <el-option
                v-for="item in saleAttr.spuSaleAttrValueList"
                :key="item.id"
                :value="`${item.baseSaleAttrId}:${item.id}`"
                :label="item.saleAttrValueName"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>
      <el-form-item label="图片列表">
        <el-table
          :data="imageList"
          border
          stripe
          @selection-change="imgSelectChange"
        >
          <el-table-column type="selection" width="50" />
          <el-table-column label="图片">
            <template v-slot="{ row }">
              <img :src="row.imgUrl" width="100" alt="" />
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="imgName"> </el-table-column>
          <el-table-column label="操作">
            <template v-slot="{ row }">
              <el-tag v-if="row.isDefault" type="danger" size="default"
                >默认图片</el-tag
              >
              <el-button
                v-else
                type="primary"
                size="default"
                @click="setDefaultImg(row)"
                :disabled="!row.isSelect"
                >设置为默认</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="default" @click="save">保存</el-button>
        <el-button size="default" @click="emits('changeShowIndex', 1)"
          >取消</el-button
        >
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { storeToRefs } from "pinia";
import { ElMessage } from "element-plus";

export default defineComponent({
  name: "SkuInfo",
});
</script>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import type {
  spuInfoItemType,
  spuSaleAttrListType,
  spuImageListType,
} from "@/api/spu";
import { reqAttrList, type attrListType } from "@/api/attr";
import {
  reqImageListBySpuId,
  reqSaleAttrBySpuId,
  type spuImageItemType,
} from "@/api/spu";
import type { skuAttrValueListType, skuImageListType, skuInfoType, skuSaleAttrValueListType } from "@/api/sku";
import { reqAddSku } from "@/api/sku";
import useCategoryStore from "@/stores/category";

//得到category的pinia中的store对象
const categoryStore = useCategoryStore();

//从pinia中拿到category的3个id,用来请求列表
const { category1Id, category2Id, category3Id } = storeToRefs(categoryStore);

//接收点击进入当前组件的spuInfo
const props = defineProps<{
  spuInfo: spuInfoItemType;
}>();

//接收切换状态的自定义事件
const emits = defineEmits<{
  (event: "changeShowIndex", index: number): void;
}>();

//定义初始值接受平台属性，销售属性，图片列表
const attrList = ref<attrListType>([]);
const saleAttrList = ref<spuSaleAttrListType>([]);
const imageList = ref<spuImageListType>([]);

//定义一个值,用来保存收集到的被选中的图片列表
const selectImageList = ref<spuImageListType>([]);

//初始化发送平台属性，销售属性，图片列表请求
onMounted(async () => {
  const promise1 = reqAttrList(
    category1Id.value as number,
    category2Id.value as number,
    category3Id.value as number
  );
  const promise2 = reqImageListBySpuId(props.spuInfo.id as number);
  const promise3 = reqSaleAttrBySpuId(props.spuInfo.id as number);

  const result = await Promise.all([promise1, promise2, promise3]);

  //给响应式数据赋值操作
  attrList.value = result[0];
  imageList.value = result[1];
  saleAttrList.value = result[2];

  //平台属性数据请求回来之后，给每一个值添加一个attrIdValueId属性，收集当前平台属性选项的选择
  attrList.value.forEach((item) => {
    item.attrIdValueId = "";
  });

  //销售属性数据请求回来之后,给每一个值添加一个saleAttrIdValueId属性,收集当前销售属性选项的选择
  saleAttrList.value.forEach((item) => {
    item.saleAttrIdValueId = "";
  });

  //给请求回来的图片列表新增属性,代表自己是否被勾选,新增属性代表是否是默认图片
  imageList.value.forEach((item) => {
    item.isSelect = false;
    item.isDefault = false;
  });
});

//初始化一个数据,用来收集参数
const skuInfo = ref<skuInfoType>({
  spuId: props.spuInfo.id as number,
  tmId: props.spuInfo.tmId as number,
  category3Id: props.spuInfo.category3Id,
  isSale: 1, //固定上架状态

  price: 0,
  skuName: "",
  skuDesc: "",
  weight: "",
  skuDefaultImg: "",

  skuImageList: [],
  skuAttrValueList: [],
  skuSaleAttrValueList: [],
});

//表格的多选框发生改变后的事件回调函数
const imgSelectChange = (selectList: spuImageListType) => {
  //参数就是:一个收集所有被选中的表格中的row数据组成的数组

  //把被选中的数据中的isSelect变成true
  selectList.forEach((item) => (item.isSelect = true));

  //收集的到参数千万不要替换原本的列表,因为原本的列表还要展示
  selectImageList.value = selectList;
};

//设置默认图片的事件回调函数
const setDefaultImg = (row: spuImageItemType) => {
  //使用排他,把其他被被选中的图片的默认取消,然后再给当前的点击的添加默认
  imageList.value.forEach((item) => {
    item.isDefault = false;
  });

  row.isDefault = true;

  //把默认图片地址设置给skuInfo中收集
  skuInfo.value.skuDefaultImg = row.imgUrl;
};

//提交事件回调函数
const save = async () => {
  //整理参数1-平台属性
  //遍历attrList,判断哪一个值拥有attrIdValueId,如果拥有则收集
  attrList.value.forEach((item) => {
    //判断当前选项是否被选择
    if (item.attrIdValueId) {
      const [attrId, valueId] = item.attrIdValueId.split(":");
      (skuInfo.value.skuAttrValueList as skuAttrValueListType).push({
        attrId: +attrId,
        valueId: +valueId,
      });
    }
  });

  //整理参数2-销售属性
  saleAttrList.value.forEach((item) => {
    if (item.saleAttrIdValueId) {
      const [saleAttrId, saleAttrValueId] = item.saleAttrIdValueId.split(":");
      (skuInfo.value.skuSaleAttrValueList as skuSaleAttrValueListType).push({
        saleAttrId: +saleAttrId,
        saleAttrValueId: +saleAttrValueId,
      });
    }
  });

  //整理参数3-图片列表
  selectImageList.value.forEach((item) => {
    (skuInfo.value.skuImageList as skuImageListType).push({
      imgName: item.imgName, //图片名称
      imgUrl: item.imgUrl, //图片地址
      spuImgId: item.id as number, //在spu中的id
      isDefault: "0", //是否是当前的默认图片
    });
  });

  await reqAddSku(skuInfo.value);

  ElMessage.success("添加sku成功");

  //返回列表页
  emits("changeShowIndex", 1);
};
</script>

<style scoped lang="scss"></style>
